package org.xinhe.toolbox.image.crop;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

/**
 * <p>Title: Cropper</p>
 * <p>Date: 17/2/6 </p>
 * <p>Description: 图片裁剪工具 </p>
 *
 * @author xinhe.sun
 */
public class Cropper {

    public static void doCrop(CropCoordinate cropCoordinate, String srcPath, String targetPath) throws IOException {
        FileInputStream is = null;
        try {
            is = new FileInputStream(srcPath);
            BufferedImage bi = doCrop(cropCoordinate, is);
            ImageIO.write(bi, "jpg", new File(targetPath));
        } finally {
            if (is != null)
                is.close();
        }
    }

    private static BufferedImage doCrop(CropCoordinate cropCoordinate, FileInputStream is) throws IOException {
        ImageInputStream iis = null;
        Iterator<ImageReader> it = ImageIO
                .getImageReadersByFormatName("jpg");
        ImageReader reader = it.next();
        iis = ImageIO.createImageInputStream(is);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        Rectangle rect = new Rectangle(cropCoordinate.getX(), cropCoordinate.getY(), cropCoordinate.getWidth(), cropCoordinate.getHeight());
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0, param);
        return bi;
    }

    public static void main(String[] args) throws Exception {

        String srcPath = "/app/tmp/qr/mdistinguish00c1010b091438969408a6759a7805eb.jpg";
        String targetPath = "/app/tmp/qr/222222.jpg";

        CropCoordinate cropCoordinate = new CropCoordinate(680, 1150, 1100, 1200);

        doCrop(cropCoordinate, srcPath, targetPath);
    }
}
